package com.io.smartappframe.thirdparties.zxing

import android.os.Bundle
import android.view.View
import com.io.base.mvc.BaseActivityMVC
import com.io.commonlib.helper.LogHelper
import com.io.commonlib.helper.ToastHelper
import com.io.smartappframe.R
import com.io.smartappframe.databinding.ActivityQRCodeBinding
import com.io.zxing.ZXingErrorCorrectionLevel
import com.io.zxing.ZXingHelper

class QRCodeActivity : BaseActivityMVC<ActivityQRCodeBinding>(), View.OnClickListener {
    override fun initView(savedInstanceState: Bundle?): ActivityQRCodeBinding {
        return ActivityQRCodeBinding.inflate(layoutInflater)
    }

    override fun initData(savedInstanceState: Bundle?) {
        mViewBinding.header.tvTitle.setText("ZXing-二维码")
        mViewBinding.header.ivToolbarBack.setOnClickListener(this)
        mViewBinding.btnRefresh.setOnClickListener(this)
    }

    override fun onClick(v: View?) {
        v?.let {
            if (it.id == R.id.iv_toolbar_back) {
                finish()
            } else if (it.id == R.id.btnRefresh) {
                val contentEntry = mViewBinding.etContent.text
                val sizeEntry = mViewBinding.etSize.text
                val correctionLevelChar =
                    mViewBinding.spinnerCorrectionLevel.selectedItem.toString()
                val correctionLevel = getCorrectionLevel(correctionLevelChar)
                val charset = mViewBinding.etCharset.text.toString()
                if (contentEntry.isNullOrEmpty()) {
                    ToastHelper.showShortToast(this, "二维码内容不能为空")
                } else if (sizeEntry.isNullOrEmpty()) {
                    ToastHelper.showShortToast(this, "二维码尺寸不能为空")
                } else {
                    val content = contentEntry.toString()
                    val size = sizeEntry.toString().toInt()
                    LogHelper.d(TAG, "content:${content}; size:${size};")
                    val bitmap =
                        ZXingHelper.getQRCodeBitmapWithExtra(
                            content,
                            size,
                            size,
                            charset,
                            correctionLevel
                        )
                    bitmap?.let {
                        mViewBinding.image.setImageBitmap(bitmap)
                    } ?: let {
                        ToastHelper.showShortToast(this, "获取二维码图片为空")
                    }
                }
            }
        }
    }

    private fun getCorrectionLevel(level: String): ZXingErrorCorrectionLevel {
        when (level) {
            "L" ->
                return ZXingErrorCorrectionLevel.L
            "M" ->
                return ZXingErrorCorrectionLevel.M
            "Q" ->
                return ZXingErrorCorrectionLevel.Q
            "H" ->
                return ZXingErrorCorrectionLevel.H
            else ->
                return ZXingErrorCorrectionLevel.L
        }
    }
}